package com.lej.core.base

import android.app.Activity
import android.content.Intent
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.LifecycleOwner
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
import kotlin.random.Random

class RequestFragment(val resultCallback: (resultCode: Int, data: Intent?) -> Unit) : Fragment() {

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        resultCallback(resultCode, data)
    }

    companion object {
        val TAG = RequestFragment::class.java.simpleName
    }

    val requestCode = Random.Default.nextInt(100, 10000)
}

suspend fun LifecycleOwner.startActivitySuspend(intent: Intent): Intent? {
    val fm = when (this) {
        is FragmentActivity -> supportFragmentManager
        is Fragment -> childFragmentManager
        else -> null
    }
    return fm?.let {
        suspendCoroutine {
            var fragment: RequestFragment? = null
            fragment = RequestFragment { resultCode, data ->
                when (resultCode) {
                    Activity.RESULT_OK -> it.resume(data)
                    Activity.RESULT_CANCELED -> it.resumeWithException(Exception("取消"))
                    else -> it.resume(data)
                }

                fragment?.let {
                    fm.beginTransaction().remove(it).commitNow()
                }
            }
            fm.beginTransaction().add(fragment, RequestFragment.TAG).commitNow()
            fragment.startActivityForResult(intent, fragment.requestCode)
        }
    }
}